<template>
  <div>
    <div class="schuling-form">
      <a-form :model="formState" ref="formAdd"
              labelAlign="left"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
      >
        <a-row :gutter="16">
<!--          <a-col :span="6">-->
<!--            <div class="form-item-border">-->
<!--              <a-form-item label="资源合同·采购" :label-col="{span: 8}" name="conId" :rules="[{ required: false, message: '请选择资源·采购合同' }]">-->
<!--                <a-select :bordered="false" @change="contractChange" v-model:value="formState.conId" placeholder="请选择资源·采购合同" :options="contractOption" />-->
<!--              </a-form-item>-->
<!--            </div>-->
<!--          </a-col>-->
          <a-col :span="6">
            <div class="form-item-border">
              <a-form-item label="装载港"  name="loadingSort" :rules="[{ required: false, message: '请选择装载港' }]">
                <a-tree-select
                    :bordered="false"
                    v-model:value="formState.loadingSort"
                    style="width: 100%"
                    :tree-data="portTree"
                    tree-checkable
                    allow-clear
                    :height="233"
                    :show-checked-strategy="SHOW_CHILD"
                    placeholder="请选择装载港"
                    tree-node-filter-prop="label"
                    :max-tag-count="1"
                />
              </a-form-item>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="form-item-border">
              <a-form-item label="装载时间" name="expectedLoadingDate" :rules="[{ required: false, message: '装载时间' }]">
                <a-date-picker :bordered="false" :locale="locale" :style="{width: '100%'}" v-model:value="formState.expectedLoadingDate" show-time value-format="YYYY-MM-DD HH:mm:ss" />
              </a-form-item>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="form-item-border">
              <a-form-item label="装载量" name="goodsQuantity" :rules="[{ required: false, message: '请输入装载量' }]">
                <a-input-number :bordered="false" v-model:value="formState.goodsQuantity" :style="{width: '100%'}" placeholder="请输入装载量"  :min="1" >
                  <template #addonAfter>
                    <a-select  style="width: 100px" v-model:value="formState.quantityUnit">
                      <a-select-option :value="1">MMBtu</a-select-option>
                      <a-select-option :value="2">m³</a-select-option>
                      <a-select-option :value="3">MT</a-select-option>
                    </a-select>
                  </template>
                </a-input-number>
              </a-form-item>
            </div>
          </a-col>
<!--          <a-col :span="6">-->
<!--            <div class="form-item-border">-->
<!--              <a-form-item label="资源合同·销售" :label-col="{span: 8}"  name="sellerResourceContract" :rules="[{ required: false, message: '请选择资源·销售合同' }]">-->
<!--                <a-select :bordered="false" @change="sellerContractChange" v-model:value="formState.sellerResourceContract"  placeholder="请选择资源·销售合同" :options="serllContractOption" />-->
<!--              </a-form-item>-->
<!--            </div>-->
<!--          </a-col>-->
          <a-col :span="6">
            <div class="form-item-border">
              <a-form-item label="卸载港"  name="unloadSort" :rules="[{ required: false, message: '请选择卸载港' }]">
                <a-tree-select
                    :bordered="false"
                    v-model:value="formState.unloadSort"
                    style="width: 100%"
                    :tree-data="unPortTree"
                    tree-checkable
                    allow-clear
                    :show-checked-strategy="SHOW_CHILD"
                    placeholder="请选择卸载港"
                    tree-node-filter-prop="label"
                    :max-tag-count="1"
                />
              </a-form-item>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="form-item-border">
              <a-form-item label="卸载时间"  name="expectedUnloadingWindow" :rules="[{ required: false, message: '卸载时间' }]">
                <a-date-picker :bordered="false" :locale="locale" :style="{width: '100%'}" v-model:value="formState.expectedUnloadingWindow" show-time value-format="YYYY-MM-DD HH:mm:ss" />
              </a-form-item>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="form-item-border">
              <a-form-item label="卸载量" name="unloadGoodsQuantity" :rules="[{ required: false, message: '请输入卸载量' }]">
                <a-input-number :bordered="false" v-model:value="formState.unloadGoodsQuantity" :style="{width: '100%'}" placeholder="请输入卸载量"  :min="1" >
                  <template #addonAfter>
                    <a-select  style="width: 100px" v-model:value="formState. unloadQuantityUnit">
                      <a-select-option :value="1">MMBtu</a-select-option>
                      <a-select-option :value="2">m³</a-select-option>
                      <a-select-option :value="3">MT</a-select-option>
                    </a-select>
                  </template>
                </a-input-number>
              </a-form-item>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="form-item-border">
              <a-form-item label="航线"  name="route" :rules="[{ required: false, message: '请输入航线' }]">
                <a-select :bordered="false" v-model:value="formState.route" mode="multiple" placeholder="请选择航线" :options="AirOptions" />
              </a-form-item>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="form-item-border">
              <a-form-item label="船速"  name="speed" :rules="[{ required: false, message: '请输入船速' }]">
                <a-input-number :bordered="false" addonAfter="节"
                                v-model:value="formState.speed" :style="{width: '100%'}" placeholder="请输入船速"
                                :max="19.5"
                                :min="1" />
              </a-form-item>
            </div>
          </a-col>
          <div class="search-flex">
            <div></div>
            <div>
              <a-button key="submit" @click="handleOk" :loading="confirmLoading" class="search-btn1">查询</a-button>
              <a-button key="back" class="border-btn"  @click="cacelModelForm">重置</a-button>
            </div>
          </div>
        </a-row>
      </a-form>
      <a-divider :style="{margin: 0}"/>
    </div>
    <div class="gantt-box">
      <div class="gantt-box-flex"  :key="'gantt-1'">
        <HightChartsShip  ref="gantt"
                          :ganttConfig="shipGanttConfig"
                          :isRedraw="isRedraw"
                          :allExport="allExport"
                          @exportImg="exportImg"
                          :planId="planId"
                          :schemeId="schemeId"
        />
      </div>
    </div>
  </div>

</template>
<script setup>
import {ref, defineProps, getCurrentInstance, onMounted, watch, reactive} from "vue";
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import HightChartsShip from './VesselGantt/HightChartsShip.vue'
const { proxy  } = getCurrentInstance()
const emit = defineEmits(['updatePlanId', 'getImgData', 'exportTable'])
import dayjs from 'dayjs'
import { TreeSelect } from 'ant-design-vue';
const SHOW_CHILD = TreeSelect.SHOW_CHILD;
const props = defineProps({
  activeKey: {
    type: String,
    default: ''
  },
  ganttData: {
    type: Object,
    default: () => {}
  },
  allExport: {
    type: Boolean,
    default: false
  },
  resSide: {
    type: String,
    default: ''
  },
  stateObj: {
    type: Object,
    default: () => {}
  }
})
const allExport = ref(props.allExport)
const gantt = ref(null)
// 贸易类型
const areas = ref([
  {
    label: '长协',
    value: 1
  },
  {
    label: '中期',
    value: 2
  },
  {
    label: '现货',
    value: 3
  }
])
// 贸易主体
const tradeareas = ref([
  {
    label: '国贸',
    value: 1
  },
  {
    label: '新贸',
    value: 2
  },
])
// 航线
const AirOptions = ref([
  {
    label: '巴拿马运河',
    value:1
  },
  {
    label: '好望角海峡',
    value:2
  },
  {
    label: '苏伊士运河',
    value:3
  }
])
const isRedraw = ref(0)
const shipGanttConfig = ref({
  // 数据源
  data: [],
  // 左侧表格列配置
  tableConfig: [],
})
const sellerGanttConfig = ref({
  data: [],
  tableConfig: []
})
const goodsGanttConfig = ref({
  data: [],
  tableConfig: []
})
watch(() => props.allExport, (newVal) => {
  allExport.value = newVal
})
watch(() => isRedraw.value, (newVal) => {
  isRedraw.value = newVal
}, {
  deep: true
})
const planId = ref('')
watch(() => planId.value, (newVal) => {
  planId.value = newVal
})
const schemeId = ref('')
const getLastData = (val) => {
  shipGanttConfig.value.tableConfig = []
  sellerGanttConfig.value.tableConfig = []
  goodsGanttConfig.value.tableConfig = []
  sellerGanttConfig.value.data = []
  shipGanttConfig.value.data = []
  goodsGanttConfig.value.data = []
  if(val.schemeInfo) {
    planId.value = val.schemeInfo.planId? val.schemeInfo.planId.toString() : ''
    schemeId.value = val.schemeInfo.schemeId? val.schemeInfo.schemeId.toString() : ''
  } else {
    planId.value = val.planId? val.planId.toString() : ''
    schemeId.value = val.schemeId? val.schemeId.toString() : ''
  }
  let shipData = val.shipNames
  console.log('shipData',shipData)
  shipData.map((item, index) => {
    shipGanttConfig.value.tableConfig.push(item.shipName)
    if (item.details.length > 0 && item.details) {
      item.details.map(child => {
        shipGanttConfig.value.data.push(Object.assign({}, child, {
          createBy: localStorage.getItem('userName'),
          id: child.id?child.id.toString() : null,
          shipContractId: child.shipContractId? child.shipContractId.toString() : null,
          y: index,
          color: child.availableStatus?colorFn(Number(child.availableStatus) - 1) : colorFn(3),
          tradeTypeLabel: tradeTypeFn(child.tradeType),
          tradeBodyLabel: tradeBodyFn(child.tradeBody),
          shipTradeBodyLabel: tradeBodyFn(child.shipTradeBody),
          sellerTradeBodyLabel: tradeBodyFn(child.sellerTradeBody),
          shipRouteLabel: shipRouteFn(child.shipRoute),
          schemeId: child.schemeId?child.schemeId.toString() : null,
          resourceContract: child.resourceContract? child.resourceContract.toString() : '',
          sellerResourceContract: child.sellerResourceContract? child.sellerResourceContract.toString() : '',
          completed: child.expectedFullLoadVoyageDays / (child.expectedFullLoadVoyageDays + child.expectedEmptyLoadVoyageDays),
          draggable: true,
          start: dayjs(child.expectedLoadingDate).valueOf(),
          end: dayjs(child.expectedEmptyReturnWindow).valueOf(),
        }))
      })
    }
  })
  console.log('甘特图', shipGanttConfig.value)
  isRedraw.value++
}
/**
 * 颜色切换
 * */
const colorFn = (i) => {
  // 可用 #165DFF 不确定可用 #FF7D00  不可用#86909c 已完成 #00B42A
  const colors = ['rgba(0,180,42,0.64)',  'rgba(255,125,0,0.64)',  'rgba(134,144,156,0.64)', 'rgba(0,40,243,0.64)', 'rgba(158,160,168,0.64)']
  return colors[i]
}
/**
 * 贸易主体赋值
 * */
const tradeBodyFn = (val) => {
  let lastVal = ''
  tradeareas.value.map(item => {
    if (item.value === val) {
      lastVal = item.label
    }
  })
  return lastVal
}
/**
 * 贸易类型赋值
 * */
const tradeTypeFn = (val) => {
  let lastVal = ''
  areas.value.map(item => {
    if (item.value === val) {
      lastVal = item.label
    }
  })
  return lastVal
}
/**
 * 航线赋值
 * */
const shipRouteFn = (val) => {
  let lastVal = []
  console.log('航线的值', val)
  if (val) {
    if (Array.isArray(val)) {
      return  val.join(',')
    } else {
      let newVal = val.split(',')
      if (newVal.length > 0 && Array.isArray(newVal)) {
        newVal.map(item => {
          AirOptions.value.map(rVal => {
            if (Number(item) === rVal.value) {
              lastVal.push(rVal.label)
            }
          })
        })
      }
      return lastVal.join(',')
    }
  }  else {
    return  lastVal
  }
}

/**
 * 导出图片
 * */
const exportImg = (val) =>{
  emit('getImgData', val)
}
// const statusUpdate = () => {
//   getChartData()
// }
const formState = reactive({
  conId: null, // 资源合同
  expectedLoadingDate: '', //装载时间
  expectedUnloadingWindow: '', //卸载时间
  flagState: null, //船旗国
  goodsQuantity: '',  //装载量
  imo: [],  //船舶
  isPotential: 1, //是否是潜在投标
  loadingSort: [], //装载港
  oilConsumption: '', //油耗
  quantityUnit: 1, //单位
  route: [], // 航线
  sellerResourceContract: null, // 销售合同
  shipModelEnd: null, // 船型起
  shipModelStart: null, // 船型止
  unloadSort: [], // 卸载港
  speed: 17, //船速
  unloadGoodsQuantity: '', //卸载量
  unloadQuantityUnit: 1, //卸载量单位
  planId: ''
})
const labelCol = ref(
    {
      style: {
        width: '60px'
      },
    },
)

const wrapperCol = ref({
  span: 22
})
const getChartData = () => {
  proxy.$api.getShipVesselChart(formState).then(res => {
    console.log('船货排布甘特图信息', res.resultObject)
    let data = res.resultObject
    if (data) {
      getLastData(res.resultObject)
      emit('updatePlanId', planId.value)
    }
  })
}
const portTree = ref([])
const portChildren = ref([])
/**
 * 获取港口信息
 * */
const unPortTree = ref([])
const unPortChildren = ref([])
const getPortsList = () => {
  portTree.value = []
  unPortTree.value = []
  proxy.$api.getPortInfo().then(res => {
    const data = res.resultObject
    data.map(item => {
      if (item.loadingPorts.length > 0) {
        let ports = {
          label: '',
          value: '',
          children: [{
            label: '',
            value: '',
          }]
        }
        item.loadingPorts.map(child => {
          Object.assign(child, {
            label: child.portNameChinese,
            value: child.id.toString(),
          })
          portChildren.value.push(child)
        })
        Object.assign(ports, {
          label: item.country,
          value: item.country,
          children: item.loadingPorts
        })
        portTree.value.push(ports)
      }
      if (item.unloadingPorts.length > 0) {
        let unPorts = {
          label: '',
          value: '',
          children: [{
            label: '',
            value: '',
          }]
        }
        console.log('455',item.unloadingPorts)
        item.unloadingPorts.map(child => {
          Object.assign(child, {
            label: child.portNameChinese,
            value: child.id.toString(),
          })
          unPortChildren.value.push(child)
          console.log('455A',item.unPortChildren)
        })
        Object.assign(unPorts, {
          label: item.country,
          value: item.country,
          children: item.unloadingPorts
        })
        unPortTree.value.push(unPorts)
      }
      console.log('港口信息',  portTree.value)
      console.log('港口信息unPortTree',  unPortTree)
    })
  })
}
const formAdd = ref()
const confirmLoading = ref(false)
const cacelModelForm = () => {
  formAdd.value.resetFields()
  formState.route = []
  formState.loadMonth = []
  getChartData()
}
const handleOk = () => {
  getChartData()
}
onMounted(() => {
  getChartData()
  getPortsList()
})
</script>

<style lang="scss" scoped>
.gantt-box-flex {
  background: #ffffff;
 // margin-top: 10px;
}
.schuling-form {
  background: #fff;
  padding: 20px;
  .search-flex {
    margin-left: 10px;
    margin-bottom: 20px;
  }
}
</style>
